<template>
  <div class="page sites" :style="{minHeight:docHeight}">
    <LeftSideBar></LeftSideBar>
    <div class="content-main clearfix">
      <ELHeader></ELHeader>
      <div class="right-content clearfix">
        <div class="breadcrumb">
          <el-breadcrumb separator=">">
            <i class="bread-ico">
              <icon name="wpexplorer"></icon>
            </i>
            <el-breadcrumb-item :to="{ path: '/' }">
              首页
            </el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/source' }" v-if="routeName === 'source'">来源列表</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/sites/'+siteId+'/edit' }" v-if="routeName === 'editSource'">来源编辑</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="btn-group">
          <el-button @click="showDialog = true" class="filter-item" size="small">+新增来源</el-button>
        </div>
        <div class="tabpane-container" ref="tabpaneContainer" v-loading.body="loading">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="来源列表" name="source">
              <ELSource type = "1" v-if="routeName === 'source'" @changeLoading="changeLoading" :loadTime="loadTime" :tabHeight="tabHeight"></ELSource>
            </el-tab-pane>
            <el-tab-pane ref="editContainer" v-if="routeName === 'editSource'" label="编辑来源" name="editSource" class="scroll" :style="'height:' + (this.tabHeight) + 'px;'">
              <AddSource v-if="routeName === 'editSource'" @changeLoading="changeLoading" :isEdit="true"></AddSource>
            </el-tab-pane>
          </el-tabs>
        </div>
        <el-dialog v-model="showDialog">
          <AddSource v-if="showDialog" v-model="addStatus"></AddSource>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<style lang="scss">
  @import '../scss/index';
    .echarts {
        height: 300px
    }

    .sites {
      .error {
        color: red;
      }
    }
    .btn-group {
      overflow: hidden;

      button {
        float: left;
      }
    }

    .content-main{
      height: 0;
      position: relative;
      float: left;
      min-height: 100%;
      width: 85%;
    }

    .short {
      max-width: 300px;
    }

    .right-content{
      padding-left: 20px;
      margin-top: 70px;
      padding-bottom: 100px;
      width: 99%;
      overflow-x: hidden;
      overflow-y: auto;
    }

    .echart-line{
      width: 100%;
      height: 400px;
    }

    .bread-ico {
      float: left;
      margin-right: 8px;
      margin-top: -8px;
      width: 30px;

      .fa-icon {
        width: 100%;
        height: 100%;
      }
    }

    .right-content {
      .el-tabs__header {
        margin-bottom: 0;
      }
      .el-tab-pane {
        padding-top: 15px;
      }
      .el-tabs__content {
        // height:  30rem;
        overflow-y: auto!important;
      }
    }

    .badge-list .el-badge {
      margin-right: 40px;
    }

    .scroll {
      width: 99%;
      overflow: hidden;
      overflow-y: auto;
    }

    .import-item {
      border-bottom: 1px solid rgb(223, 230, 236);
    }

    .short.el-select {
      min-width: 300px;
    }

    .el-input.short-filter-input {
      width: 160px;
    }

    .filter-body .filter-item {
      float: left;
      .el-input__inner {
        height: 28px;
      }

      &.mgl {
        margin-left: 10px;
      }

      &.el-pagination {
        padding: 0;
      }
    }
</style>

<script>
import Header from 'components/AdminHeader'
import LeftSideBar from 'components/LeftSideBar'
import SelectSite from 'components/SelectSite'
import Source from 'components/Source'
import CustomProfile from 'components/CustomProfile'
import AddSource from 'components/AddSource'

import { Col } from 'element-ui'
import { mapState, mapActions } from 'vuex'
import { Popover, Breadcrumb, BreadcrumbItem,
  Tabs, TabPane, Button, Dialog, Upload, Table,
  TableColumn, Pagination, Form, FormItem, Select, Input, Option } from 'element-ui'
import Config from '../config/common'
import Icon from 'vue-awesome/components/Icon.vue'
import 'vue-awesome/icons/wpexplorer'
// import commonFilter from '../common/sites'

export default {
  data () {
    return {
      siteData: [],
      siteId: null,
      loading: false,
      load: true,
      showUserPanel: false,
      docHeight: window.innerHeight + 'px',
      screenWidth: document.body.clientWidth,
      resize: false,
      activeName: 'sites',
      showDialog: false,
      loadTime: 0,
      uploadAction: '',
      fileList: [],
      filterData: {
        channel_id: null
      },
      queryData: {
        page_index: 1
      },
      isInit: false,
      tabHeight: 500,
      responseList: {},
      currentPage: 1,
      siteDetail: {},
      addStatus: '',
      showFileList: false
    }
  },

  watch: {
    routeName (routeName) {
      console.log(routeName, 'routeName')
      this.activeName = routeName
    },
    addStatus (value) {
      if (value === 'success') {
        this.showDialog = false
        this.loadTime = Math.random()
      }
    },
    screenWidth (val) {
      if (!this.timer) {
        this.screenWidth = val
        this.timer = true
        const that = this

        setTimeout(function () {
          that.resize = !that.resize
          that.timer = false
        }, 400)
      }
    },
    // switchSource (value) {
    //   if (value === false) {
    //     this.loading = true
    //     setTimeout(() => {
    //       this.initialize()
    //     }, 2000)
    //   }
    // },
    showDialog (value) {
      // if (value === false) {
        // this.emptyDatas()
        // this.getSource()
      // }
    },
    uploadDialog (value) {
      console.log(value)
      if (value === false) {
        this.emptyDatas()
        setTimeout(() => {
          this.getSource()
        }, 1000)
      }
      this.tableData = []
      this.fileList = []
      this.responseList = {}
        // this.$refs.upload.clearFiles()
      // }
    },
    dataDictionary (val) {

    }
  },
  methods: {
    changeLoading (loading) {
      this.loading = loading
      console.log('changeLoading')
    },
    handleSizeChange (val) {
      this.queryData['page_size'] = val
      this.page_size = val
      // hack
      this.setSizeInputVal(val)
      console.log(`每页 ${val} 条`)
      this.emptyDatas()
      this.getSource()
    },
    changeFilterData () {
      if (this.filterData.channel_id && this.filterData.channel_id.replace(' ', '')) {
        this.emptyList()
        this.getSource()
      } else {
        console.debug('no filter data')
        this.emptyDatas()
        this.getSource()
      }
    },
    emptyList () {
      this.list = []
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveCustom(this.siteDetail).then((response) => {
            if (response.data.errcode === 0) {
              this.$router.push({ path: '/sites/' + this.siteId })
              this.isEdit = false
              this.activeName = 'profile-detail'
              this.initCustom(this.siteId)
              this.emptyDatas()
              this.getSource()
            }
          }).catch((err) => {
            console.log(err)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    },
    setSizeInputVal (val) {
      const sizeInput = this.$refs.pagination.$el.getElementsByClassName('el-input__inner')[0]
      val = val + ' ' + '条/页'
      sizeInput.value = val
    },
    handleCurrentChange (val) {
      // if (this.isInit === false && parseInt(this.$route.query.page_index)) {
      //   val = parseInt(this.$route.query.page_index)
      //   this.currentPage = val
      //   this.isInit = true
      //   return
      // }
      this.queryData['page_index'] = val
      console.log(`当前页: ${val}`)
      this.emptyDatas()
      this.getSource()
    },
    handleClick (tab, event) {
      this.$router.push({ name: this.activeName })
      console.log(tab, this.activeName)
    },
    view ($scope) {
      this.initCustom($scope.row.id)
      this.$router.push({ path: '/sites/' + $scope.row.id })
      this.siteId = $scope.row.id
      this.activeName = 'profile-detail'
    },
    editSource ($scope) {
      this.siteDetail = {}
      this.$router.push({ path: '/sites/' + $scope.row.id, query: { type: 'edit' }})
      this.siteId = $scope.row.id
      this.activeName = 'profile-edit'
      this.isEdit = true
      this.initCustom($scope.row.id)
    },
    emptyDatas () {
      this.list = []
      this.filterData = {}
    },
    reverse (object) {
      var NewObj = {}
      var keysArr = Object.keys(object)
      for (var i = keysArr.length - 1; i >= 0; i--) {
        NewObj[keysArr[i]] = object[keysArr[i]]
      }
      return NewObj
    },
    filterPage (value, row) {
      console.log(value, row)
      return row.page_index === value
    },
    removeEmptyValues (dataObj) {
      var freshObject = {}
      for (const key in dataObj) {
        if (dataObj[key]) freshObject[key] = dataObj[key]
      }
      return freshObject
    },
    getSource (params) {
      this.loading = true
      const filterData = this.removeEmptyValues(this.filterData)
      const queryData = Object.assign({}, filterData, this.queryData, params || {})
      this.requestSource(queryData).then((response) => {
        const resData = response.data
        // this.initPageFilters(resData.results)
        if (resData.errcode === 0 && resData.results && resData.results.data) {
          this.list = response.data.results.data
          // this.queryData['page_index'] = resData.results.currentPage
          this.total = resData.results.total
          this.currentPage = resData.results.current_page
          console.log('resData.results', this.currentPage, resData)
        } else {
          console.log('空数据')
        }
        this.loading = false
        this.addStatus = ''
      }).catch((error) => {
        // console.log(error)
        console.log(error)
        this.loading = false
        this.addStatus = ''
      })
    },
    initPageFilters (pageData) {
      const totalPage = Math.ceil(pageData['total'] / this.queryData.page_size)
      for (let i = 1; i <= totalPage; i++) {
        this.filters.push({
          value: i,
          text: i
        })
      }
    },
    initCustom (id) {
      this.getCustom({ id: id }).then((response) => {
        console.log(response.data.errcode)
        if (response.data.errcode === 0) {
          this.siteDetail = response.data.results
          this.siteData = this.formateCustom(this.siteDetail)
        }
        this.loading = false
      }).catch((err) => {
        console.log(err)
        this.loading = false
      })
    },
    initialize () {
      const windowHeight = window.innerHeight
      const offsetTop = this.$refs['tabpaneContainer'].offsetTop
      this.tabHeight = windowHeight - offsetTop - 60
      // this.loading = true
    },
    // ...commonFilter,
    ...mapActions({
      requestSource: 'getSource',
      // getDictionary: 'getDictionary',
      getCustom: 'getCustom',
      saveCustom: 'saveCustom',
      updateMenuIndex: 'updateMenuIndex'
    })
  },
  mounted: function () {
    this.siteId = this.$route.params.id

    this.uploadAction = Config.CRM_API_HOST + '/users/' + this.token + '/import'
    // this.setSizeInputVal(this.queryData.page_size)
    // this.getDictionary()
    this.updateMenuIndex('source')
    this.activeName = this.routeName
    this.initialize()

    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        this.screenWidth = window.screenWidth
      })()
    }
  },

  components: {
    ELHeader: Header,
    LeftSideBar: LeftSideBar,
    'ELSource': Source,
    CustomProfile: CustomProfile,
    [Popover.name]: Popover,
    [Breadcrumb.name]: Breadcrumb,
    [Tabs.name]: Tabs,
    [TabPane.name]: TabPane,
    [BreadcrumbItem.name]: BreadcrumbItem,
    [Button.name]: Button,
    [Dialog.name]: Dialog,
    [Upload.name]: Upload,
    [Table.name]: Table,
    [TableColumn.name]: TableColumn,
    [Pagination.name]: Pagination,
    [Form.name]: Form,
    [Select.name]: Select,
    [Input.name]: Input,
    [Option.name]: Option,
    [FormItem.name]: FormItem,
    SelectSite,
    AddSource,
    'el-col': Col,
    'icon': Icon
  },
  computed: {
    ...mapState({
      token: state => state.auth.user.token,
      // dataDictionary: state => state.site.data_dictionary,
      // switchSource: state => state.site.switch_site,
      route: state => state.route,
      path: state => state.route.path,
      routeName: state => state.route.name === 'home' ? 'source' : state.route.name
    })
  }
}

</script>
